package com.computergames.server.server.handler;

import com.computergames.server.domain.ClientState;
import com.computergames.server.message.CreateRoomResponseMessage;
import com.computergames.server.message.JoinRoomRequestMessage;
import com.computergames.server.message.JoinRoomResponseMessage;
import com.computergames.server.server.session.Room;
import com.computergames.server.server.session.RoomSessionFactory;
import com.computergames.server.server.session.RoomSessionService;
import com.computergames.server.service.Interface.CheckAndUpdateClientState;
import com.computergames.server.util.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;

import java.util.List;

@ChannelHandler.Sharable
public class JoinRoomRequestMessageHandler extends SimpleChannelInboundHandler<JoinRoomRequestMessage> {
    CheckAndUpdateClientState checkAndUpdateClientState;
    private static final AttributeKey<String> USER_ROOM_KEY = AttributeKey.valueOf("USER_ROOM");
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, JoinRoomRequestMessage msg) throws Exception {
        checkAndUpdateClientState = SpringUtil.getBean(CheckAndUpdateClientState.class);
        if(checkAndUpdateClientState.checkState(channelHandlerContext, ClientState.MODE_SELECTED)){
            String roomName = msg.getRoomName();
            String username = msg.getUsername();
            RoomSessionService roomSessionService = RoomSessionFactory.getRoomSession();
            Boolean isFull = roomSessionService.joinMember(roomName, username);
            if(isFull == null){
                channelHandlerContext.writeAndFlush(new JoinRoomResponseMessage(false, "房间不存在"));
            }else if(isFull){
                List<Channel> channels = roomSessionService.getMembersChannel(roomName);
                for (Channel channel : channels) {
                    channel.writeAndFlush(new JoinRoomResponseMessage(true, roomName + "房间人数已满，请准备"));
                    checkAndUpdateClientState.updateState(channel, ClientState.GAME_READY);
                }
            }else {
                channelHandlerContext.channel().attr(USER_ROOM_KEY).set(roomName);
                channelHandlerContext.writeAndFlush(new JoinRoomResponseMessage(true, "加入" + roomName + "房间成功"));
            }
        } else if(checkAndUpdateClientState.checkState(channelHandlerContext, ClientState.ROOM_JOINED)){
            channelHandlerContext.writeAndFlush(new JoinRoomResponseMessage(false, "你已经加入了房间，请勿重复加入"));
        }else {
            channelHandlerContext.writeAndFlush(new JoinRoomResponseMessage(false, "请先选择模式再加入房间"));
        }

    }
}
